(function(window, angular, undefined){
	'use strict';
	var auth = angular.module('auth', []);
	var config = {
		moduleName : auth.name,
		tpl_folder : 'template',
	}
	var api = {
		user : 'users/users/user',
		login: 'users/users/login',
		logout :'users/users/logout'
	}
	var tpl_path = [rootConfig.moduleDir,config.moduleName,config.tpl_folder].join('/');
	var loginState = ['login'].join('');
	var loginController = [config.moduleName,'login'].join('.');
	
	auth.config(function ($stateProvider, $urlRouterProvider) {
		$stateProvider
			.state(loginState,{
		    	url : '/login',
		    	templateUrl : [tpl_path,'login.html'].join('/'),
		    	controller: loginController,
		    })
		    .state('logout',{
		    	url: '/logout',
		    	template : '<div class="message-loading-overlay"><i class="fa-spin ace-icon fa fa-spinner orange2 bigger-160"></i></div>',
		    	controller : function($state,$http,$scope){
					var url = [rootConfig.baseUrl,api.logout].join('/');
					$http.get(url).success(function(data){
						$state.go(loginState);
					});
		    	}
		    })

	})
	auth.controller(loginController, ['$scope','rootService','authService','$state','$http','$location', 
		function ($scope,rootService,authService,$state,$http,$location)
	{
		$scope.formData = {};
		$scope.signup = function(formData){
			var data = {
				email : formData.email,
				username : formData.username,
				password : formData.password
			};
			var flag = rootService.validateForm(data);
			if(flag){
				authService.Users.add(data).success(function(res){
					if(res.status==false){
						box.alert('Thông báo','Có lỗi trong quá trình đăng kí!','red');
					}else{
						$state.go(loginState);
					}
				});		
			}
		}
		$scope.login = function(formData){
			var data = {
				username : formData.username,
				password : formData.password,
				save 	 : formData.save ? 'y' : 'n'
			}
			var flag = rootService.validateForm(data);
			if(flag){
				rootConfig.loading(true,'#loginForm');
				authService.Users.login(data).success(function(res){
					if(res.status==false){
						box.alert('Đăng nhập thất bại!');
					}else{
						$state.go('home');
					}
				});
			}
			rootConfig.loading(false);
		}
		
	}])
	auth.service('authService', ['$http',function ($http) {
		return {
			Users : {
				add : function(data){
					var url = [rootConfig.baseUrl,api.user].join('/');
					return $http.post(url,data);
				},
				login : function(data){
					var url = [rootConfig.baseUrl,api.login].join('/');
					return $http.post(url,data);
				},
				logout : function(){
					var url = [rootConfig.baseUrl,api.logout].join('/');
					return $http.get(url);
				}
			}
		}
	}])
})(window, window.angular);